//
//  SupplierOrderViewController.m
//  SafeFoodManagerDemo
//
//  Created by ios-1 on 2018/3/15.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "SupplierOrderViewController.h"
#import "GetRegisterInforModel.h"
#import "AddRecruitViewController.h"
#import "HelpDetailViewController.h"
#import "AddAcountViewController.h"
#import "SearchShopViewController.h"
#import "RightShopTableViewCell.h"
#import "RegisterShopModel.h"
@interface SupplierOrderViewController ()
@property(nonatomic,copy)NSString*SearchKeyWord;
@property(nonatomic,copy)NSString*positionId;      //当前岗位ID
@property(nonatomic,copy)NSString*shopId;          //当前岗位商户ID
@property(nonatomic,assign)BOOL is_selectPosition; //是否点击当前岗位
@property(nonatomic,strong)RegisterShopModel *shopModel;
//是否编辑过。
@property(nonatomic,assign)BOOL IS_CHANGE;

@end

@implementation SupplierOrderViewController



- (void)viewDidLoad {
    self.IS_CHANGE = false;
    
    [super viewDidLoad];
   
    
    self.homeTableView.estimatedRowHeight=70;
    [self.homeTableView registerNib:[UINib nibWithNibName:@"RightShopTableViewCell" bundle:nil] forCellReuseIdentifier:@"RightShopCell"];
    self.homeTableView.tableHeaderView = [self tabHeadView];
    [self.homeTableView.mj_header beginRefreshing];
    
    [self.view addSubview:self.Footview];
    
    self.Reqmodel.currentPage=1;
    [self loadTotalDatas];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
     DLog("控制器出现++++++");
    
    
}

- (UIView*)tabHeadView
{
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.1)];
    headview.backgroundColor = [UIColor clearColor];
    
    return headview;
}
#pragma mark-tablevie代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    
    GoodListData *data=self.dataArr[indexPath.row];
   

    
    RightShopTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RightShopCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.addCartBlock = ^(NSInteger count, BOOL add) {
        data.quantity = count;
        
        if(count == 0)
        {
            [self refreshData:self.dataArr];
        }else{
            [self refreshFootView];
        }
    };
    
    
    //添加的代码。
    
    cell.addCartBlock1 = ^(float count, BOOL add) {
        data.quantity = count;
        
        if(count == 0)
        {
            [self refreshData:self.dataArr];
        }else{
            [self refreshFootView];
        }
    };
    cell.priceChangeBlock1=^(float count, NSInteger index){
        
        
        if (_on_operation) {
            data.price = count;
        }else{
            if (_is_Out) {
                data.salePrice = count;
                
                
            }else{
                
                data.price = count;
                
            }
            
            
        }
       
        
        [self refreshFootView];
        
        
        
    };
    
    
    
    
    [cell refreshData:data ISOut:self.is_Out];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
    //    return UITableViewAutomaticDimension;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
    view.tintColor=TBColorTableViewBg;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.1;
    
}

#pragma mark-搜索跳转事件
-(void)PushChangeStatueVC
{
    [self selectShop];
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self selectShop];
}

//选商品
- (void)selectShop
{
    SearchShopViewController *Patro=[SearchShopViewController new];
    JobListModel *list=[JobListModel new];
    list.pageOn = YES;
    list.pageSize = 500;
    list.currentPage = 1;
    list.ptype = @"1";
    list.shopId= [LoginStatuesModel shopId];
    list.supplierId = self.supplierId;
    
    NSDictionary* params=[NSMutableDictionary dictionary];
    [params setValue:[NSString stringWithFormat:@"%ld",self.supplierId] forKey:@"supplierId"];
    list.params = [HelpWay dictionaryToJSON:params];
    
    Patro.ishidenSearch = NO;
    Patro.Reqmodel = list;
    Patro.isEdit= YES;
    Patro.isdeleMore=NO;
    Patro.isGroupStyle=YES;
    Patro.searchName=@"请输入商品名称";
    Patro.AddBtnTitle = @"确定";
    Patro.title= @"新增出货";
    Patro.is_Out = self.is_Out;
    Patro.editArray = self.dataArr;
    Patro.addCartBlock = ^(NSMutableArray *dataArray) {
        
        [self refreshData:dataArray];
    };
    
    [self.navigationController pushViewController:Patro animated:YES];
}
/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
//    self.Reqmodel.currentPage=1;
//
//    [self.homeTableView.mj_footer resetNoMoreData];
//
//    [self loadDatas];
    
    [self NetRequestSuccess:self scrollView:self.homeTableView];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
//    self.Reqmodel.currentPage++;
//
//    [self loadDatas];
    [self NetRequestSuccess:self scrollView:self.homeTableView];
}

-(void)loadTotalDatas
{
    
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodListModel *InforModel=[GoodListModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            
            if (InforModel.data.count==0) {
                
                self.Type=TBNODateType;
            }else{
                [self.totalArray addObjectsFromArray:InforModel.data];
                [self loadDatas];
            }
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}
-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:self.requrl andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
        
            NSDictionary *dic = [NSDictionary dictionary];
            if([responseObject[@"data"] count] > 1)
            {
                dic = responseObject[@"data"][1];
                NSArray *arr = dic[@"list"];
                
                for(int i=0;i<arr.count;i++)
                {
                    GoodListData *data = [GoodListData mj_objectWithKeyValues:arr[i]];
                    
                    if (self.on_operation) {
                        data.salePrice = data.price;
                    }
                    
                    [self.dataArr addObject:data];
                }
            }
            
            if (self.dataArr.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=HBselectShop;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
            }else if (self.dataArr.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
//                if(self.is_Out)//出货才会进行价格替换
//                {
//                    [self handleData:self.totalArray];
//                }
                
                [self.homeTableView reloadData];
                [self refreshFootView];
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}

#pragma ****************脚底视图********************
- (UIView*)Footview
{
    if(_Footview == nil)
    {
        _Footview = [[UIView alloc]init];
        
        if (kDevice_Is_iPhoneX) {
            
            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64-34, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }else{
            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }
        _Footview.backgroundColor = [UIColor whiteColor];
        
        UILabel *linelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        linelab.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        UILabel *totalMoneyLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
        totalMoneyLab.text = @"合计：0";
        totalMoneyLab.textColor = [UIColor redColor];
        totalMoneyLab.font = [UIFont systemFontOfSize:14];
        
        UILabel *totalCountLab = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetHeight(_Footview.frame)/2, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
        totalCountLab.text = @"品种数量：0";
        totalCountLab.textColor = [UIColor darkGrayColor];
        totalCountLab.font = [UIFont systemFontOfSize:14];
        
        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        nextBtn.backgroundColor = TBColorProvideBtnbg;
        nextBtn.enabled = NO;
        nextBtn.frame = CGRectMake(CGRectGetMaxX(totalMoneyLab.frame), 0, 90, CGRectGetHeight(_Footview.frame));
        [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [nextBtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [_Footview addSubview:linelab];
        [_Footview addSubview:self.totalMoneyLab = totalMoneyLab];
        [_Footview addSubview:self.totalCountLab = totalCountLab];
        [_Footview addSubview:self.nextButton = nextBtn];
    }
    return _Footview;
}


- (void)nextClick:(UIButton*)sender
{
    
    GetRegisterInforModel *model=[GetRegisterInforModel new];
    
    model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    model.orderId = self.Reqmodel.orderId;
    
    model.token=[LoginStatuesModel getUserToken];
    
    AddAcountViewController *addPeople=[AddAcountViewController new];
    
    addPeople.requrl= self.requrl;
    
    addPeople.Reqmodel=model;
    
    addPeople.postUrl=self.postUrl;
    
    addPeople.title=@"确认订单";
    
    addPeople.BtnStr=@"新增";
    
    addPeople.OptionSussStr=@"新增成功";
    
    addPeople.isOrder = YES;
    
    addPeople.moneyStr = self.moneyStr;
    
    addPeople.countStr = self.countStr;
   
    
    
    if (_on_operation) {
        
    }else{
        if (_is_Out) {
            [self handleData:self.dataArr];
        }
        
        
    }
  
    
    
    addPeople.dataArray = self.dataArr;
    
    
    
    
    addPeople.supplierId = self.supplierId;
    
    addPeople.block=^()
    {
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:addPeople animated:YES];
}

- (void)refreshFootView
{
    
    CGFloat totalPrice = 0;
    for(GoodListData *data in self.dataArr)
    {
        
        if (self.on_operation) {
            totalPrice += data.quantity*data.price;
        }else{
            
            if(self.is_Out)
            {
                totalPrice += data.quantity*data.salePrice;
                
                
            }else{
                totalPrice += data.quantity*data.price;
            }
            
        }
        
       
    }
    
    self.moneyStr = totalPrice;
    self.countStr = self.dataArr.count;
    
    self.totalMoneyLab.text = [NSString stringWithFormat:@"合计：%.2f",totalPrice];
    self.totalCountLab.text = [NSString stringWithFormat:@"品种数量：%zd",self.dataArr.count];
    self.nextButton.enabled =  self.dataArr.count >0?YES:NO;
}

- (void)handleData:(NSMutableArray*)dataArray
{
    for(GoodListData *data in dataArray)
    {
        for(GoodListData *editdata in self.dataArr)
        {
            if(data.goodsId == editdata.goodsId)
            {
                editdata.price = data.salePrice;
                editdata.salePrice = data.salePrice;
            }
        }
    }
    
}

- (void)refreshData:(NSMutableArray*)dataArray
{
    
    
    
    NSMutableArray *newArr = [NSMutableArray array];
    for(GoodListData *data in dataArray)
    {
        if(data.quantity >0)
        {
            [newArr addObject:data];
        }
    }
    
   // [self.dataArr removeAllObjects];
    [self.dataArr addObjectsFromArray:newArr];

    
    if(self.dataArr.count)
    {
        self.Type=HBselectShop;
    }
    [self.homeTableView reloadData];
    [self refreshFootView];
}
- (NSMutableArray*)totalArray
{
    if(_totalArray==nil)
    {
        _totalArray = [NSMutableArray array];
    }
    return _totalArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
